package com.zlll.winner.service.bbs.async;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zlll.winner.business.model.bbs.BbsSubject;
import com.zlll.winner.business.model.bbs.BbsUserComment;
import com.zlll.winner.mapper.bbs.BbsSubjectMapper;
import com.zlll.winner.mapper.bbs.BbsUserCommentMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * <p>
 * 话题异步服务实现类
 * </p>
 *
 * @author Walert
 * @since 2019-09-12
 */
@Service
@Async
@Slf4j
public class BbsSubjectAsyncService {

    @Resource
    private BbsSubjectMapper subjectMapper;

    private int count(long id) {
        BbsSubject bbsSubject = subjectMapper.selectById(id);

        BbsSubject updateObj = new BbsSubject();
        updateObj.setUpdateTime(System.currentTimeMillis());
        updateObj.setPosts(bbsSubject.getPosts() + 1);
        int update = subjectMapper.update(updateObj,
                Wrappers.<BbsSubject>lambdaQuery()
                        .eq(BbsSubject::getId, id)
                        .eq(BbsSubject::getUpdateTime, bbsSubject.getUpdateTime()));
        return update;
    }


    @Async
    public void countPosts(Long id) throws InterruptedException {
        int res = 0;
        int sum = 10;
        while(res == 0 && sum > 0){
            res = count(id);
            if(res == 0 ) Thread.sleep(500L);
            sum --;
        }
        log.error("统计话题帖子数量完毕。");
    }

}
